<?php

namespace app\model;

use app\exception\UserNotFoundException;
use app\exception\UserPasswordErrorFoundException;
use app\exception\UserTokenExpiredException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\helper\Str;
use think\Model;

class User extends Model
{

    /**
     * 用户登录
     * @param $studentNumber string 学号
     * @param $password string 密码
     * @return array 用户信息
     * @throws UserNotFoundException 用户不存在异常
     * @throws UserPasswordErrorFoundException 用户密码错误异常
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function login($studentNumber,$password){

        // 查询用户
        $user = self::where("student_number",$studentNumber)->find();

        // 用户不存在
        if(!$user){
            throw new UserNotFoundException();
        }

        // 密码错误
        if(!password_verify($password, $user->password)){
            throw new UserPasswordErrorFoundException();
        }

        // 生成token
        $token = Str::random(32);

        // 更新token
        $user->save([
            'token' => $token
        ]);

        // 返回用户信息
        return [
            'user' => $user->hidden(['password'])
        ];
    }

    /**
     * 验证登录状态
     * @throws UserTokenExpiredException token过期
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function isLogin($token){
        // 查询token是否有效
        $user = self::where("token",$token)->find();


        // toke过期
        if(!$user){
            throw new UserTokenExpiredException();
        }

        // 返回用户信息
        return [
            'user' => $user->hidden(['password'])
        ];

    }
}